import { LocalStorage } from "./storage";

/**
 * 初始化应用数据
 */
export async function initializeApp() {
  // 初始化用户会话
  try {
    const userStore = await getUserStore();
    userStore.initUser();
    userStore.loadReaderSettings();
  } catch (error) {
    console.error("用户初始化失败:", error);
  }

  console.log("应用初始化完成");
}

/**
 * 获取存储统计信息
 */
export function getStorageStats() {
  const users = LocalStorage.getUsers();
  const currentUser = LocalStorage.getCurrentUser();
  const token = LocalStorage.getToken();

  return {
    totalUsers: users.length,
    hasCurrentUser: !!currentUser,
    hasToken: !!token,
    currentUserId: currentUser?.id,
    storageKeys: {
      users: "novel_app_users",
      currentUser: "novel_app_current_user",
      token: "novel_app_token",
    },
  };
}

/**
 * 检查本地存储健康状态
 */
export function checkStorageHealth() {
  try {
    // 测试读写权限
    const testKey = "storage_test";
    const testValue = { test: true, timestamp: Date.now() };

    localStorage.setItem(testKey, JSON.stringify(testValue));
    const retrieved = JSON.parse(localStorage.getItem(testKey) || "{}");
    localStorage.removeItem(testKey);

    if (retrieved.test !== true) {
      throw new Error("Storage read/write test failed");
    }

    return {
      healthy: true,
      message: "本地存储正常",
    };
  } catch (error) {
    return {
      healthy: false,
      message: "本地存储异常: " + (error as Error).message,
    };
  }
}

// 动态导入用户store（避免循环依赖）
async function getUserStore() {
  const { useUserStore } = await import("@/stores/user");
  return useUserStore();
}
